// pages/user/user.js
const util = require('../../utils/util.js')
const settings = require('../../datas/settings')
const app = getApp()
const userDao = require('../../dao/userDao')
Page({
  data: {
    hasUserInfo: false,
    avatarUrl: "../../assets/user-man.png",
    userInfo: {},
    settings: settings.data,
    hidden: true
  },

  onLoad() {
    //获取 本地用户信息
    let userInfo = util.hasCache(app.keys.userInfo)
    app.data.userInfo = userInfo
    let currentUser = util.hasCache(app.keys.currentUser)
    app.data.currentUser = currentUser
    if (userInfo) {
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true,
        //当前用户信息初始化了，就用当前用户的头像
        avatarUrl: currentUser ? currentUser.avatarUrl : "../../assets/user-man.png",
      })
    }
  },

  // 点击 登录，去获取微信的用户信息
  bindLogin() {
    this.getUserProfile('e')
  },

  /**
   * 查看资料
   */
  bindUserInfo() {
    //已经缓存了 当前用户数据
    if (app.data.currentUser) {
      wx.navigateTo({
        url: '/pages/user-card/user-card?edit=1&user=' + JSON.stringify(app.data.currentUser),
      })
    } else {
      wx.navigateTo({
        url: '../user-data-add/user-data-add',
      })
    }
  },

  /**
   * 点击 选择头像
   */
  bindImage() {
    let that = this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log('chooseImage-1: ' + res)
        //上传头像
        that.uploadImage(res.tempFilePaths[0])
        //显示头像
        that.setData({
          avatarUrl: res.tempFilePaths[0]
        })
      }
    })
  },

  uploadImage(filePath) {
    wx.showLoading()
    let that = this
    let time = new Date().getTime()
    wx.cloud.uploadFile({
      cloudPath: app.data.currentUser._id + '-' + time + '.png', // 上传至云端的路径
      filePath, // 小程序临时文件路径
      success: res => {
        console.log('uploadImage-2: ' + res)
        // 返回文件 ID
        that.updateAvatarUrl(res.fileID)
      },
      fail: res => {
        wx.hideLoading()
        wx.showToast({
          title: '上传失败',
        })
      }
    })
  },

  updateAvatarUrl(avatarUrl) {
    userDao.update(app.data.currentUser._id, {
      avatarUrl: avatarUrl
    }).then(res => {
      console.log('updateAvatarUrl-3: ' + res.stats)
      app.data.currentUser.avatarUrl = avatarUrl
      util.setCache(app.keys.currentUser, app.data.currentUser)
      wx.hideLoading()
      wx.showToast({
        title: '上传成功',
      })
    }).catch(e => {
      wx.hideLoading()
      wx.showToast({
        title: '上传失败',
      })
    })
  },

  mSetData() {
    this.setData({
      userInfo: app.data.userInfo,
      hasUserInfo: true,
      avatarUrl: app.data.currentUser.avatarUrl
    })
  },
  openLikePage() {
    this.mSetData()
    wx.navigateTo({
      url: '../like/like',
    })
  },
  openAlbumPage() {
    this.mSetData()
    wx.navigateTo({
      url: '../user-album/user-album',
    })
  },
  openContactPage() {
    this.mSetData()
    wx.navigateTo({
      url: '../user-contact/user-contact',
    })
  },


  triggeclick(e) {
    let title = e.detail;
    switch (title) {
      case "收藏":
        if (!util.checkLogin()) {
          wx.showToast({
            title: '亲，登录后查看个人收藏',
            icon: 'none'
          })
          return
        }
        if (!util.checkCurrentUser(this.openLikePage)) {
          return
        }

        // userDao.add({'name': '小李', 'age': 30}).then(res => console.log(res) )
        // userDao.where({'name': '小明2'}).then(res => console.log(res.data))
        // userDao.where({'_openid': 'oDMFW5bP9r8KwM5xXv7C_kIWk-HM'}).then(res => console.log(res.data))
        // userDao.count().then(res => console.log(res.total))
        // userDao.whereCount({height: '160CM'}).then(res => console.log(res) )
        // userDao.doc('82afc00a6231ff2e000a86d26142f35e')
        // .then(res => console.log(res.data))
        // .catch(e => console.log(e))
        // userDao.update('d4107ab16232cfee002dd87e4818d018', {age: 300}).then(res => console.log(res))
        // userDao.set('d4107ab16232cfee002dd87e4818d018', {age: 3000}).then(res => console.log(res))
        // userDao.remove('d2fe6f206232cfed002a5e7102a1f5c7').then(res => console.log(res))
        break;
      case "相册":
        if (!util.checkLogin()) {
          wx.showToast({
            title: '亲，登录后查看个人相册',
            icon: 'none'
          })
          return
        }
        if (!util.checkCurrentUser(this.openAlbumPage)) {
          return
        }
        break;
      case "联系方式":
        if (!util.checkLogin()) {
          wx.showToast({
            title: '亲，登录后上传个人名片',
            icon: 'none'
          })
          return
        }
        if (!util.checkCurrentUser(this.openContactPage)) {
          return
        }
        break;
    }
  },

  /**
   * 获取用户信息
   */
  async getUserInfo() {
    let res = await userDao.where({
      '_openid': app.data.userInfo._openid
    })
    console.log(res)
    wx.hideLoading()
    let user = res.data[0]
    if (user) {
      //更新currentUser
      app.data.currentUser = user
      util.setCache(app.keys.currentUser, user)
      this.setData({
        avatarUrl: app.data.currentUser.avatarUrl,
      })
    }

  },

  /**
   * 获取 OpenId
   */
  getOpenId(userInfo) {
    wx.showLoading({
      title: '正在加载...',
    });
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      data: {
        type: 'getOpenId'
      }
    }).then((res) => {
      //更新 userInfo
      userInfo._openid = res.result.openid
      util.setCache(app.keys.userInfo, userInfo)
      app.data.userInfo = userInfo
      this.setData({
        userInfo: userInfo,
        hasUserInfo: true
      })
      this.getUserInfo()
    }).catch((e) => {
      console.log(e);
      wx.hideLoading();
    });
  },

  /**
   * 获取用户信息 {微信昵称，微信头像}
   */
  getUserProfile(e) {
    // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    wx.getUserProfile({
      desc: '展示用户信息',
      success: (res) => {
        console.log(res)

        this.getOpenId(res.userInfo)
      }
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '赶快来相亲吧',
      path: 'pages/home/home',
      success: function (res) {
        console.log('ddd')
      }
    }
  }

})